package util;


import android.os.Handler;
import android.os.Message;
import android.util.Log;


import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;


import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpClient {


    public static void uploadFile(final String actionUrl, final File uploadFile, final Handler handler, final int what) {
        new Thread(){

            @Override
            public void run() {
                super.run();
                OkHttpClient okHttpClient = new OkHttpClient();
                // file是要上传的文件 File()
                RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), uploadFile);
                // 不仅可以支持传文件，还可以在传文件的同时，传参数
                MultipartBody requestBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("file", uploadFile.getName(), fileBody)
                        .build();
                Request request = new Request.Builder().url(actionUrl).post(requestBody).build();
                Response response = null;
                try {
                    response = okHttpClient.newCall(request).execute();
                    if(!response.isSuccessful()) {

                    }
                    String result = response.body().string();
                    response.body().close();
                    Message msg = new Message();
                    msg.what=what;
                    msg.obj = result;
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }.start();



    }
}
